<template>
    <div class="log-records">
        <!-- 分页控件 -->
        <Pagination 
            :current-page="page" 
            :total-pages="totalPages" 
            @page-change="goToPage" 
        />

        <!-- 记录列表 -->
        <div class="records-list">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-container">
                <van-loading type="spinner" color="#1989fa" size="24px">加载中...</van-loading>
            </div>
            
            <template v-else>
                <div v-if="records.length > 0">
                    <div v-for="(record, index) in records" :key="index" class="record-item">
                        <div class="record-header">
                            <div class="record-type">
                                <van-tag :type="getTypeTag(record.logType)">
                                    {{ getTypeText(record.logType) }}
                                </van-tag>
                            </div>
                            <div class="record-date">{{ record.createTime }}</div>
                        </div>
                        
                        <div class="record-content">
                            <div class="content-item">
                                <div class="label">{{ getSummaryLabel(record.logType) }}：</div>
                                <div class="text">{{ record.weeklySummary }}</div>
                            </div>
                            
                            <div class="content-item">
                                <div class="label">{{ getPlanLabel(record.logType) }}：</div>
                                <div class="text">{{ record.nextWeekPlan }}</div>
                            </div>

                            <div class="content-item" v-if="record.feedback">
                                <div class="label">反馈：</div>
                                <div class="text">{{ record.feedback }}</div>
                            </div>
                        </div>

                        <div class="record-footer">
                            <div class="evaluation">
                                <span class="label">自我评价：</span>
                                <van-rate 
                                    :size="16" 
                                    v-model="record.selfEvaluation"
                                    color="#1E9FFF"
                                    void-icon="star"
                                    void-color="#eee"
                                    :count="4"
                                    readonly
                                />
                                <span class="rate-text">{{ getRateText(record.selfEvaluation) }}</span>
                            </div>
                            
                            <div class="attachments" v-if="record.fileList?.length || record.imageList?.length">
                                <div class="label">附件：</div>
                                <div class="attachment-list">
                                    <template v-if="record.imageList?.length">
                                        <van-image
                                            v-for="(image, imgIndex) in record.imageList"
                                            :key="'img-' + imgIndex"
                                            :src="image.url"
                                            width="60"
                                            height="60"
                                            fit="cover"
                                            radius="4"
                                            @click="previewImage(record.imageList, imgIndex)"
                                        />
                                    </template>
                                    
                                    <div 
                                        v-for="(file, fileIndex) in record.fileList" 
                                        :key="'file-' + fileIndex"
                                        class="file-item"
                                        @click="downloadFile(file)"
                                    >
                                        <van-icon :name="getFileIcon(file.fileType)" size="20" />
                                        <span class="file-name">{{ file.name }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 空状态 -->
                <div v-else class="empty-state">
                    <van-empty description="没有更多了" />
                </div>
            </template>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { 
    Tag as VanTag,
    Rate as VanRate,
    Image as VanImage,
    Icon as VanIcon,
    Empty as VanEmpty,
    showToast,
    Popup as VanPopup,
    Loading as VanLoading,
    showImagePreview
} from 'vant';
import request from '@/utils/request';
import apiUrls from '@/config/apiUrls'; 
import Pagination from '@/Pages/compontents/Pagination.vue';

// 列表加载相关
const loading = ref(false);
const page = ref(1);
const pageSize = 10;
const records = ref([]);
const total = ref(0);

// 计算总页数
const totalPages = computed(() => {
    return Math.ceil(total.value / pageSize);
});

// 跳转到指定页
const goToPage = (newPage) => {
    if (newPage < 1 || newPage > totalPages.value) return;
    const oldPage = page.value;
    page.value = newPage;
    loadRecords().catch(() => {
        // 如果加载失败，恢复原来的页数
        page.value = oldPage;
    });
};

// 组件挂载时加载数据
onMounted(() => {
    loadRecords();
});

// 加载记录数据
const loadRecords = async () => {
    try {
        loading.value = true;
        // 添加一个小的延迟，确保加载状态可见
        await new Promise(resolve => setTimeout(resolve, 100));
        const {data} = await request.post(apiUrls.zhjy.getLogRows, {pageNum: page.value, pageSize: pageSize});
        const data1 = data['data']
        const msg = data1['msg']
        const rows = data1['rows']
        total.value = data1['total']
        const datails = data['datails']
        console.log("总数:", total.value);
        console.log("消息:", msg);
        console.log("列表:", rows);
        const listData = []

        datails.forEach(row => {
            const data2 = row['data']
            
            const item = {
                logType: data2['recordType'],
                createTime: data2['recordDay'],
                weeklySummary: data2['todaySummary'],
                nextWeekPlan: data2['nextSummary'],
                feedback: data2['feedback'],
                selfEvaluation: getEvaluation(data2['selfEvaluate']),
                imageList: [],
                fileList: []
            };
            
            // 处理文件列表
            if (data2['fileList'] && data2['fileList'].length > 0) {
                data2['fileList'].forEach(file => {
                    // 根据文件类型分类
                    if (['jpg', 'jpeg', 'png', 'gif'].includes(file.fileType.toLowerCase())) {
                        item.imageList.push({
                            url: file.filePath,
                            name: file.fileName
                        });
                    } else {
                        item.fileList.push({
                            name: file.fileName,
                            url: file.filePath,
                            fileType: file.fileType
                        });
                    }
                });
            }
            
            listData.push(item);
        });

        records.value = listData;
        
    } catch (error) {
        console.error('获取记录失败:', error);
        showToast('获取记录失败，请重试');
        // 抛出错误，让调用者知道加载失败
        throw error;
    } finally {
        loading.value = false;
    }
};

const getEvaluation =(value)=>{
    switch(value) {
        case '1': return 2;
        case '2': return 3;
        case '3': return 4;
        case '4': return 1;
        default: return 2;
    }
}

// 获取类型标签样式
const getTypeTag = (type) => {
    switch(type) {
        case '1': return 'primary';
        case '2': return 'success';
        case '3': return 'warning';
        default: return 'default';
    }
};

// 获取类型文本
const getTypeText = (type) => {
    switch(type) {
        case '1': return '日报';
        case '2': return '周报';
        case '3': return '月报';
        default: return '未知';
    }
};

// 获取评分文本
const getRateText = (value) => {
    switch(value) {
        case 1: return '尚需努力';
        case 2: return '一般';
        case 3: return '良好';
        case 4: return '优秀';
        default: return '';
    }
};

// 获取总结标签
const getSummaryLabel = (type) => {
    switch(type) {
        case '1': return '今日总结';
        case '2': return '本周总结';
        case '3': return '本月总结';
        default: return '总结';
    }
};

// 获取计划标签
const getPlanLabel = (type) => {
    switch(type) {
        case '1': return '明日计划';
        case '2': return '下周计划';
        case '3': return '下月计划';
        default: return '计划';
    }
};

// 预览图片
const previewImage = (images, index) => {
    showImagePreview({
        images: images.map(img => img.url),
        startPosition: index,
        closeable: true
    });
};

// 下载文件
const downloadFile = (file) => {
    window.open(file.url, '_blank');
};

// 获取文件图标
const getFileIcon = (fileType) => {
    const type = fileType ? fileType.toLowerCase() : '';
    switch(type) {
        case 'doc':
        case 'docx':
            return 'description';
        case 'xls':
        case 'xlsx':
            return 'orders-o';
        case 'pdf':
            return 'bookmark-o';
        case 'ppt':
        case 'pptx':
            return 'video-o';
        case 'zip':
        case 'rar':
            return 'archive';
        default:
            return 'description';
    }
};
</script>

<style scoped>
.log-records {
    padding: 16px;
    background: #f5f5f5;
    min-height: 100vh;
}

.records-list {
    position: relative;
    min-height: 200px;
}

.loading-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    z-index: 1;
}

.loading-container .van-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
}

.loading-container .van-loading__spinner {
    margin: 0;
}

.loading-container .van-loading__text {
    color: #1989fa;
    font-size: 14px;
    margin-top: 8px;
    text-align: center;
    width: 100%;
    display: block;
}

.empty-state {
    padding: 40px 0;
}

.record-item {
    background: white;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    opacity: 0;
    transform: translateY(20px);
    animation: fadeInUp 0.5s ease forwards;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.record-item:nth-child(1) {
    animation-delay: 0.1s;
}

.record-item:nth-child(2) {
    animation-delay: 0.2s;
}

.record-item:nth-child(3) {
    animation-delay: 0.3s;
}

.record-item:nth-child(4) {
    animation-delay: 0.4s;
}

.record-item:nth-child(5) {
    animation-delay: 0.5s;
}

.record-item:nth-child(6) {
    animation-delay: 0.6s;
}

.record-item:nth-child(7) {
    animation-delay: 0.7s;
}

.record-item:nth-child(8) {
    animation-delay: 0.8s;
}

.record-item:nth-child(9) {
    animation-delay: 0.9s;
}

.record-item:nth-child(10) {
    animation-delay: 1s;
}

.record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.record-date {
    color: #999;
    font-size: 14px;
}

.record-content {
    margin-bottom: 16px;
}

.content-item {
    margin-bottom: 12px;
}

.content-item:last-child {
    margin-bottom: 0;
}

.label {
    color: #666;
    margin-bottom: 4px;
    font-weight: 500;
}

.text {
    color: #333;
    line-height: 1.5;
    white-space: pre-wrap;
}

.record-footer {
    border-top: 1px solid #f5f5f5;
    padding-top: 12px;
}

.evaluation {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
}

.rate-text {
    color: #666;
    font-size: 14px;
}

.attachments {
    margin-top: 12px;
}

.attachment-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
}

.file-item {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    background: #f5f5f5;
    border-radius: 4px;
    cursor: pointer;
}

.file-item:hover {
    background: #e8e8e8;
}

.file-name {
    font-size: 14px;
    color: #666;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>